﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Order.MicroService.Api.Config
{
    public class HttpClientService
    {
        private readonly HttpClient _httpClient;

        public HttpClientService(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }


        public async Task<HttpResponseMessage> GetInfoTest()
        {
            //StringContent stringContent = new StringContent();

            return await _httpClient.PostAsync("/api/Account/PlaceOrders", null);
        }

        /// <summary>
        /// Get 请求无参
        /// </summary>
        /// <returns></returns>
        public async Task<HttpResponseMessage> TestGetMethod()
        {
            return await _httpClient.GetAsync("/api/Account/TestGetInfo");
        }
        /// <summary>
        /// Get 请求有参数
        /// </summary>
        /// <param name="parameters">参数字典，可为空</param>
        /// <param name="token">请求头</param>
        /// <returns></returns>
        public async Task<HttpResponseMessage> TestGetMethodWithValues(Dictionary<string, string> parameters, string token)
        {
            var requestUri = "/api/Account/TestGetInfoWithValue";
            //添加请求头
            if (!string.IsNullOrWhiteSpace(token))
            {
                _httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
            }

            //拼接地址
            if (parameters != null)
            {
                var strParam = string.Join("&", parameters.Select(o => o.Key + "=" + o.Value));
                requestUri = string.Concat(requestUri, '?', strParam);
            }

            return await _httpClient.GetAsync(requestUri);
        }

        /// <summary>
        /// Post 请求有参数 x-www-form-urlencoded
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public async Task<string> GetInfoByStringContent(Dictionary<string, string> parameters)
        {
            // x-www-form-urlencoded 的两种写法
            //第一种写法 StringContent 
            //var strParam = string.Join("&", parameters.Select(o => o.Key + "=" + o.Value));
            var formStr = string.Join('&', parameters.Select(kv => $"{kv.Key}={HttpUtility.UrlEncode(kv.Value)}"));
            var formCtx = new StringContent(formStr, Encoding.UTF8, "application/x-www-form-urlencoded");

            //第二种写法 FormUrlEncodedContent
            FormUrlEncodedContent formUrlEncoded = new FormUrlEncodedContent(parameters);


            var result = string.Empty;
            var response = await _httpClient.PostAsync("/api/Account/TestGetInfoWithValue", formUrlEncoded);
            response.EnsureSuccessStatusCode();
            if (response.IsSuccessStatusCode)
            {
                result = response.Content.ReadAsStringAsync().Result;
            }
            return result;
        }

        /// <summary>
        /// Post 请求有参数 Json
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public async Task<string> GetInfoByJson(Dictionary<string, string> parameters)
        {
            var jsonStr = JsonConvert.SerializeObject(parameters);
            var jsonCtx = new StringContent(jsonStr, Encoding.UTF8, "application/json");
            var result = string.Empty;
            var response = await _httpClient.PostAsync("/api/Account/GetInfoByJson", jsonCtx);
            response.EnsureSuccessStatusCode();
            if (response.IsSuccessStatusCode)
            {
                result = response.Content.ReadAsStringAsync().Result;
            }
            return result;
        }

        /// <summary>
        /// Post 请求有参数 form-data类型
        /// </summary>
        /// <param name="name"></param>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<string> GetInfoByFormData(string name,string Id)
        {
            MultipartFormDataContent formData = new MultipartFormDataContent();
            formData.Add(new StringContent(name), "name");
            formData.Add(new StringContent(Id), "Id");
            var result = string.Empty;
            var response = await _httpClient.PostAsync("/api/Account/GetInfoByFormData", formData);

            // Test when using form-data,the boundary what`s shows in the ContentType of the Headers
            var form = new MultipartFormDataContent();
            string boundary = string.Format("--{0}", DateTime.Now.Ticks.ToString("x"));
            form.Headers.Add("ContentType", $"multipart/form-data, boundary={boundary}");

            response.EnsureSuccessStatusCode();
            if (response.IsSuccessStatusCode)
            {
                result = response.Content.ReadAsStringAsync().Result;
            }
            return result;           
        }


        public async Task<string> TestPolly()
        {
            try
            {
                var result = string.Empty;
                var response = await _httpClient.GetAsync("/api/Account/TestPolly");
                //response.EnsureSuccessStatusCode();
                if (response.IsSuccessStatusCode)
                {
                    result = response.Content.ReadAsStringAsync().Result;
                }
                return result;
            }
            catch (Exception ex)
            {
                Console.WriteLine("抛出异常");
                var type = ex.GetType().ToString();
                return type;
            }
        }
    }
}
